package com.shuoyue.ycgk.ui.main.main_flowable;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.cardview.widget.CardView;

import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.appbar.CollapsingToolbarLayout;
import com.google.android.material.tabs.TabLayout;
import com.shuoyue.ycgk.R;
import com.shuoyue.ycgk.appcatch.SPUtils;
import com.shuoyue.ycgk.base.BaseMvpFragment;
import com.shuoyue.ycgk.base.baseadapter.IndexFragmentStateAdapter;
import com.shuoyue.ycgk.entity.DayTaget;
import com.shuoyue.ycgk.entity.Rule;
import com.shuoyue.ycgk.entity.Type;
import com.shuoyue.ycgk.entity.UserInfo;
import com.shuoyue.ycgk.ui.common.CommonModuleContract;
import com.shuoyue.ycgk.ui.common.RuleContract;
import com.shuoyue.ycgk.ui.common.TagetContract;
import com.shuoyue.ycgk.ui.course.SpecialCourseActivity;
import com.shuoyue.ycgk.ui.main.contract.MainTabContract;
import com.shuoyue.ycgk.ui.main.today_count.TodayActivity;
import com.shuoyue.ycgk.ui.mine.learnprogress.DealClassProgressActivity;
import com.shuoyue.ycgk.utils.XDateUtils;
import com.shuoyue.ycgk.views.SportProgressView;
import com.shuoyue.ycgk.views.TabLayoutUtil;
import com.shuoyue.ycgk.views.dialog.SetDayTagetDialog;
import com.shuoyue.ycgk.views.dialog.common.BigHintDialog;
import com.shuoyue.ycgk.views.viewpager_scroll.SuperViewPager;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class FragmentMainTabAps extends BaseMvpFragment<MainTabContract.Presenter>
        implements MainTabContract.View, CommonModuleContract.View, TagetContract.View, RuleContract.View {
    @BindView(R.id.tab_layout)
    TabLayout tabLayout;
    @BindView(R.id.view_pager)
    SuperViewPager viewPager;
    //    @BindView(R.id.refreshlayout)
//    SmartRefreshLayout refreshlayout;
    @BindView(R.id.sportview1)
    SportProgressView sportview1;
    @BindView(R.id.q_done)
    TextView qDone;
    @BindView(R.id.q_total)
    TextView qTotal;
    @BindView(R.id.sportview2)
    SportProgressView sportview2;
    @BindView(R.id.timedone)
    TextView timedone;
    @BindView(R.id.sportview3)
    SportProgressView sportview3;
    @BindView(R.id.rightRate)
    TextView rightRate;
    @BindView(R.id.setPlan)
    TextView setPlan;
    @BindView(R.id.cardView)
    CardView cardView;
    @BindView(R.id.myClasse)
    Button myClasse;
    @BindView(R.id.lay_dealcourse)
    LinearLayout layDealcourse;
    @BindView(R.id.toolbar_layout)
    CollapsingToolbarLayout toolbarLayout;
    @BindView(R.id.app_bar)
    AppBarLayout appBar;
    @BindView(R.id.join_num)
    TextView joinNum;


    IndexFragmentStateAdapter indexFragmentAdapter;
    List<BaseMvpFragment> fragmentMainItems;
    boolean isAtTop = false;  //设置手势识别监听器;转换方式
    CommonModuleContract.Presenter comPresenter;
    TagetContract.Presenter tagetPresenter;
    Type type;
    RuleContract.Presenter rulePresenter;

    //    int setMinut, setQuestion, setRate;
    DayTaget dayTaget;


    @Override
    public void initParams(Bundle bundle) {
        type = (Type) bundle.getSerializable("questionType");
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_main_home_tab_collaps;
    }

    @Override
    protected void initView() {
        appBar.addOnOffsetChangedListener((AppBarLayout.BaseOnOffsetChangedListener) (appBarLayout, i) -> {
            if (i >= 0) {
                //顶部
                ((FragmentMainBaseType) getParentFragment()).changeRefreshEnable(true);
            } else {
                ((FragmentMainBaseType) getParentFragment()).changeRefreshEnable(false);
            }
        });
        UserInfo userInfo = SPUtils.getUserInfo(mContext);
        if (userInfo != null && userInfo.getIsAgreement() == 1) {
            setPlan.setVisibility(View.GONE);
            myClasse.setVisibility(View.VISIBLE);
        } else {
            setPlan.setVisibility(View.VISIBLE);
            myClasse.setVisibility(View.GONE);
        }
    }

    public void refresh() {

        tagetPresenter.getTaget(type.getId(), null);
//        tagetPresenter.getTaget(type.getId(), XDateUtils.format(System.currentTimeMillis(), "yyyy-MM-dd"));
        //刷子页面
        if (indexFragmentAdapter != null
                && indexFragmentAdapter.getCurrentFragment() != null
                && tabLayout.getTabCount() != 0) {
            FragmentMainItem fragmentMainItem = ((FragmentMainItem) indexFragmentAdapter.getCurrentFragment());
            fragmentMainItem.refresh();
        } else {
//            comPresenter.getBaseModels(1);
            comPresenter.getChildType(type.getId());
        }
    }


    @Override
    protected void initData() {
        mPresenter = new MainTabContract.Presenter();
        mPresenter.attachView(this);
        comPresenter = new CommonModuleContract.Presenter();
        comPresenter.attachView(this);
        tagetPresenter = new TagetContract.Presenter();
        tagetPresenter.attachView(this);
        rulePresenter = new RuleContract.Presenter();
        rulePresenter.attachView(this);
        tagetPresenter.getTaget(type.getId(),
                XDateUtils.format(System.currentTimeMillis(), "yyyy-MM-dd")
        );
    }

    private void setType(List<Type> mTypes) {
        fragmentMainItems = new ArrayList<>();
        for (Type topType : mTypes) {
            fragmentMainItems.add(FragmentMainItem.getInstance(topType, type));
        }
        indexFragmentAdapter = new IndexFragmentStateAdapter(getChildFragmentManager(),
                fragmentMainItems);
//        TabLayoutUtil.setTabTextSizeWhenSelect(tabLayout);
        tabLayout.setupWithViewPager(viewPager);
        viewPager.setOffscreenPageLimit(1);
        viewPager.setAdapter(indexFragmentAdapter);
        viewPager.setCurrentItem(0);
        //加载成子分类后,加载公共数据(模考/banner)
        TabLayoutUtil tabLayoutUtil = new TabLayoutUtil();
        tabLayoutUtil.setTabTextSizeWhenSelect(tabLayout, mTypes);
    }

    public static FragmentMainTabAps getInstance(Type type) {
        FragmentMainTabAps fragmentMainTab = new FragmentMainTabAps();
        Bundle bundle = new Bundle();
        bundle.putSerializable("questionType", type);
        fragmentMainTab.setArguments(bundle);
        return fragmentMainTab;
    }

    SetDayTagetDialog dayTagetDialog;

    @OnClick({R.id.setPlan, R.id.setDayTaget, R.id.myClasse, R.id.sportview1, R.id.sportview2, R.id.sportview3, R.id.rule})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.myClasse:
                startActivity(new Intent(mContext, DealClassProgressActivity.class));
                break;
            case R.id.rule:
                rulePresenter.getRule(3);
                break;
            case R.id.setPlan:
                startActivity(new Intent(mContext, SpecialCourseActivity.class));

                break;
            case R.id.setDayTaget:
                if (dayTagetDialog == null)
                    dayTagetDialog = new SetDayTagetDialog(mContext, (minut, questionNum, scoreRate) -> {
                        tagetPresenter.setDayTaget(type.getId(), minut, questionNum, scoreRate);
                    });
                if (dayTaget != null)
                    dayTagetDialog.setInit(dayTaget.getSetMinuteNum(), dayTaget.getSetQuestionNum(), dayTaget.getSetAccuracyNum());
                dayTagetDialog.show();
                break;
            case R.id.sportview2:
                TodayActivity.start(mContext, type.getId(), 1);
                break;
            case R.id.sportview1:
            case R.id.sportview3:
                TodayActivity.start(mContext, type.getId(), 0);

                break;
        }
    }


    @Override
    public void setBaseType(List<Type> baseTypes) {


    }

    @Override
    public void setTabType(List<Type> type) {
        setType(type);
    }

    @Override
    public void setTodayTaget(DayTaget dayTaget) {
        this.dayTaget = dayTaget;
        qDone.setText(String.valueOf(dayTaget.getQuestion()));
        qTotal.setText(String.valueOf(dayTaget.getSetQuestionNum()));
        timedone.setText(String.valueOf(dayTaget.getMinute()));
        rightRate.setText(String.valueOf(dayTaget.getAccuracy() + "%"));
        rightRate.setTextColor(dayTaget.getAccuracy() > dayTaget.getSetAccuracyNum()
                ? Color.parseColor("#1C90F5")
                : Color.parseColor("#FE5118"));
        sportview1.setProgress(dayTaget.getQuestionPercent());
        sportview2.setProgress(dayTaget.getMinutePercent());
        sportview3.setProgress(dayTaget.getAccuracyPercent());
        joinNum.setText(String.valueOf(dayTaget.getTotalPerson()));
//        setMinut = dayTaget.getMinuteNum();
//        setQuestion = dayTaget.getSetQuestionNum();
//        setRate = dayTaget.getSetAccuracyNum();
    }

    @Override
    public void userSetTodayTaget() {
        tagetPresenter.getTaget(type.getId(),
                null
        );
    }

    //<editor-folder desc="手势相关操作">


    //</editor-folder desc="手势相关操作">

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if ((isVisibleToUser && isResumed())) {
            onResume();
        } else if (!isVisibleToUser) {
            onPause();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (getUserVisibleHint()) {
            //TODO give the signal that the fragment is visible
            if (viewPager.getChildCount() == 0) {
                comPresenter.getChildType(type.getId());
            }
            tagetPresenter.getTaget(type.getId(),
                    null
            );
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        //TODO give the signal that the fragment is invisible
    }

    @Override
    public void setRule(Rule userInfo) {
        BigHintDialog hintDialog = new BigHintDialog(mContext, "协议班规则",
                userInfo.getContent(), Gravity.LEFT);
        hintDialog.show();
    }
}
